<template>
  <el-dialog
    title="新增"
    :visible.sync="visible"
    width="75vw"
    top="8vh"
    :close-on-click-modal="false"
  >
    <div class="boxsty">
      <el-row>
        <el-form
          :model="dataForm"
          :rules="dataRule"
          ref="dataForm"
          label-width="130px"
        >
          <el-col :span="24">
            <el-col :span="6">
              <el-form-item label="任务书名称:" prop="workAssignName">
                <el-input
                  v-model="dataForm.workAssignName"
                  placeholder="任务书名称"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="任务书有效期:" required>
                <el-col :span="10">
                  <el-form-item prop="workAssignYxqq">
                    <el-date-picker
                      v-model="dataForm.workAssignYxqq"
                      type="date"
                      value-format="yyyy-MM-dd"
                      placeholder="开始日期"
                      style="width: 100%"
                    ></el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="4">
                  <div class="text-center">至</div>
                </el-col>
                <el-col :span="10">
                  <el-form-item prop="workAssignYxqz">
                    <el-date-picker
                      v-model="dataForm.workAssignYxqz"
                      type="date"
                      value-format="yyyy-MM-dd"
                      placeholder="结束日期"
                      style="width: 100%"
                    ></el-date-picker>
                  </el-form-item>
                </el-col>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="模板名称:" prop="templateId">
                <el-select
                  v-model="dataForm.templateId"
                  placeholder="模板名称"
                  class="xiaLa"
                  style="width: 100%"
                  :clearable="true"
                  @change="fngetTempList"
                >
                  <el-option
                    v-for="(item, index) in categoryList"
                    :key="index"
                    :label="item.templateName"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-col>
        </el-form>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-col :span="12">
            <div>
              <div
                style="
                  float: left;
                  width: 118px;
                  margin-right: 12px;
                  text-align: right;
                "
              >
                <el-button
                  type="text"
                  icon="el-icon-user-solid"
                  @click="addUser('fy')"
                ></el-button>
              </div>
              <div style="float: left">
                <div>
                  <el-badge
                    :hidden="fayuerendataList.length < 3"
                    :value="fayuerendataList.length"
                    class="item"
                    style="font-size: 16px; color: #303745"
                  >
                    被考核人
                  </el-badge>
                </div>
                <div>
                  <span class="mg-r15" v-for="item in fayuerendataList">
                    {{ item.fayueName }}
                  </span>
                </div>
              </div>
            </div>
          </el-col>
        </el-col>
      </el-row>
    </div>
    <div style="padding: 10px 0; display: flex; justify-content: space-between">
      <div style="float: left">
        <el-tooltip
          class="item"
          effect="dark"
          content="指标库"
          placement="top-start"
        >
          <el-button
            plain
            icon="el-icon-plus"
            type="primary"
            @click="addBtn"
            circle
          ></el-button>
        </el-tooltip>

        <el-tooltip
          class="item"
          effect="dark"
          content="批量删除"
          placement="top-start"
        >
          <el-button
            plain
            type="danger"
            icon="el-icon-delete"
            @click="deleteBatch()"
            circle
          ></el-button>
        </el-tooltip>
      </div>
      <div>
        <div style="display: flex">
          <!-- <el-button type="primary" plain @click="copyZhibiao('fy')"
            >复用指标</el-button
          > -->
          <el-button
            type="primary"
            plain
            @click="saveBtn"
            v-loading.fullscreen.lock="fullscreenLoading"
            >确 定</el-button
          >
          <el-button type="primary" @click="closeBtn" plain>取 消</el-button>
        </div>
      </div>
    </div>
    <el-table
      :data="dataList"
      border
      style="width: 100%"
      min-height="60vh"
      ref="table"
    >
      <el-table-column
        type="selection"
        width="55"
        header-align="center"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="zhibiaoType"
        label="指标类别"
        min-width="90"
        header-align="center"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="zhibiaoName"
        label="指标名称"
        min-width="120"
        show-overflow-tooltip
        header-align="center"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="weight"
        label="权重(%)"
        min-width="110"
        header-align="center"
        align="center"
      >
        <template slot-scope="scope">
          <el-input
            type="number"
            min="0"
            max="100"
            oninput="value=value.replace(/[^\d]/g,0);if(isNaN(value))value=0;if(value>100)value=100;
                                      if(value<0)value=0;if(value.charAt(0)==0&&value.charAt(1)!='')value=0"
            v-model="scope.row.weight"
            placeholder="请输入内容"
          />
        </template>
      </el-table-column>
      <el-table-column
        prop="formulaId"
        label="计算公式"
        min-width="180"
        header-align="center"
        align="center"
      >
        <template slot-scope="scope">
          <el-select
            v-model="scope.row.formulaId"
            placeholder="请选择"
            :clearable="true"
          >
            <el-option
              v-for="item in formulaOptions"
              :key="item.id"
              :label="item.gsMc"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column
        prop="targetValue"
        label="目标值"
        min-width="200"
        header-align="center"
        align="center"
      >
        <template slot-scope="scope">
          <el-input
            type="textarea"
            :rows="3"
            style="white-space: pre-wrap"
            v-model="scope.row.targetValue"
            placeholder="请输入内容"
          />
        </template>
      </el-table-column>
      <el-table-column
        prop="unit"
        label="单位"
        min-width="100"
        header-align="center"
        align="center"
      >
        <template slot-scope="scope">
          <el-input v-model="scope.row.unit" placeholder="请输入内容" />
        </template>
      </el-table-column>
      <el-table-column
        prop="targetValueType"
        label="完成值获取方式"
        min-width="180"
        header-align="center"
        align="center"
      >
        <template slot-scope="scope">
          <el-select v-model="scope.row.targetValueType">
            <el-option
              v-for="item in typeList"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column
        prop="khrName"
        label="考核人"
        min-width="180"
        header-align="center"
        align="center"
      >
        <template slot-scope="scope">
          <div>
            {{ scope.row.khrName }}
            <i
              style="margin-left: 5px; color: #1a71fb; cursor: pointer"
              @click="chooseBtn(scope.row)"
              class="el-icon-edit-outline"
            ></i>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        prop="dataProviderId"
        label="数据提供部门/人"
        min-width="180"
        header-align="center"
        align="center"
      >
        <template slot-scope="scope">
          <div>
            <span v-if="scope.row.tgLx == 2">
              {{ scope.row.targetUserName }}
            </span>
            <span v-else>
              {{ scope.row.dataProvider }}
            </span>
            <i
              style="margin-left: 5px; color: #1a71fb; cursor: pointer"
              @click="sjtgBtn('ndts', 'ndcj', scope.row, scope.$index)"
              class="el-icon-edit-outline"
            ></i>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        prop="isziping"
        label="是否自评"
        min-width="120"
        show-overflow-tooltip
        header-align="center"
        align="center"
      >
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isziping"
            active-color="#13ce66"
            inactive-color="#CCCCCC"
            active-value="true"
            inactive-value="false"
            active-text="是"
            inactive-text="否"
            :disabled="iszipingShow"
          >
          </el-switch>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
      title="任务书指标库"
      :visible.sync="dialogVisible"
      width="80%"
      append-to-body
    >
      <zhibiaoTable ref="zhibiaoRef" @func="getRow"></zhibiaoTable>
      <span slot="footer" class="dialog-footer">
        <el-button
          plain
          type="primary"
          @click="addZhibiao"
          v-loading.fullscreen.lock="fullscreenLoadingadd"
          >添 加</el-button
        >
        <el-button plain @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
    <sortingPerChooseDialog
      :sortingPerChooseDialogData="sortingPerChooseDialogData"
      @sortingPerChooseDialogChild="sortingPerChooseDialogChild"
    ></sortingPerChooseDialog>
    <!-- 数据提供部门 -->
    <FormulateDialog
      ref="formulateDialog"
      @submitfy="submitfysjtgbm"
    ></FormulateDialog>
    <UserCommonSelect ref="usercomment" @submitfy="submitfy"></UserCommonSelect>
  </el-dialog>
</template>

<script>
import zhibiaoTable from "@/views/hetongrenwu/hetong/hetongyeji/zhibiaoTable";
import UserCommonSelect from "@/views/hetongrenwu/components/usercomment-select";
import sortingPerChooseDialog from "@/views/hetongrenwu/components/sortingPerChooseDialog.vue";
import FormulateDialog from "@/views/hetongrenwu/hetong/hetongyeji/hetonghtxxdjb/formulateDialog";
import { saveWorkAssign } from "@/api/hetongrenwu/book/bookcj";
import { getTempListForgzrws } from "@/api/hetongrenwu/hetongyeji/hetongnd";
import {
  getFormula,
  addHetongHtzb,
} from "@/api/hetongrenwu/hetongyeji/hetongzb";
import { effective } from "@/api/hetongrenwu/hetongyeji/hetongnd";
export default {
  components: {
    UserCommonSelect,
    zhibiaoTable,
    sortingPerChooseDialog,
    FormulateDialog,
  },
  data() {
    var checkDate = (rule, value, callback) => {
      if (value) {
        if (
          new Date(value.replace(/-/g, "/")) <
          new Date(this.dataForm.workAssignYxqq.replace(/-/g, "/"))
        ) {
          callback("结束日期不能小于开始日期!");
        } else {
          callback();
        }
      } else {
        callback("请选择结束日期");
      }
    };
    var checkDateKai = (rule, value, callback) => {
      if (value) {
        if (
          new Date(value.replace(/-/g, "/")) >
          new Date(this.dataForm.workAssignYxqz.replace(/-/g, "/"))
        ) {
          callback("开始日期不能大于结束日期!");
        } else {
          callback();
        }
      } else {
        callback("请选择开始日期");
      }
    };
    return {
      visible: false,
      dialogVisible: false,
      dataForm: {},
      categoryList: [],
      fayuerendataList: [],
      formulaOptions: [],
      typeList: [
        { name: "手工填报", value: "0" },
        { name: "自动获取", value: "1" },
      ],
      dataList: [],
      newRows: [],
      jsonData: "",
      fullscreenLoading: false,
      fullscreenLoadingadd: false,
      sortingPerChooseDialogData: {},
      providerIndex: "",
      iszipingShow:"",
      dataRule: {
        workAssignName: [
          { required: true, message: "任务书名称不能为空", trigger: "blur" },
        ],
        workAssignYxqq: [{ validator: checkDateKai, trigger: "change" }],
        workAssignYxqz: [{ validator: checkDate, trigger: "change" }],
        templateId: [
          { required: true, message: "请选择模板名称", trigger: "change" },
        ],
      },
    };
  },
  watch: {},
  created() {},
  methods: {
    getXiaLa() {
      getFormula().then((res) => {
        this.formulaOptions = res.data.data;
      });
    },
    // 获取下拉
    fneffective() {
      effective({
        tagName: "工作任务书",
      }).then((res) => {
        this.categoryList = res.data.data;
      });
    },
    init() {
      this.fneffective();
      this.getXiaLa();
      this.visible = true;
    },
    //增加人员
    addUser(type) {
      this.jsonData = JSON.stringify(this.fayuerendataList);
      this.$nextTick(() => {
        this.$refs.usercomment.init("12", type, this.jsonData);
      });
    },
    sjtgBtn(type, lastPage, row, index) {
      this.jsonData = JSON.stringify();
      this.providerIndex = index;
      this.$nextTick(() => {
        this.$refs.formulateDialog.init("12", type, this.jsonData, lastPage);
      });
    },
    submitfysjtgbm(data) {
      console.log(data);
      this.dataList[this.providerIndex].tgLx = data.tgLx;
      if (data.tgLx == "1") {
        this.dataList[this.providerIndex].dataProvider =
          data.selectorgdata[0].deptName;
        this.dataList[this.providerIndex].dataProviderId =
          data.selectorgdata[0].deptId;
        this.dataList[this.providerIndex].targetUserName =
          data.selectorgdata[0].ryName;
        this.dataList[this.providerIndex].targetUserId =
          data.selectorgdata[0].userId;
      } else if (data.tgLx == "2") {
        this.dataList[this.providerIndex].targetUserName =
          data.tableDataUser[0].ryName;
        this.dataList[this.providerIndex].targetUserId =
          data.tableDataUser[0].userId;
        this.dataList[this.providerIndex].dataProvider =
          data.tableDataUser[0].deptName;
        this.dataList[this.providerIndex].dataProviderId =
          data.tableDataUser[0].deptId;
      }
      this.resetDataList();
    },
    chooseBtn(row) {
      this.sortingPerChooseDialogData = {
        visible: true,
        types: "gzrws",
        perLsit: {
          userName: row.khrName,
          userId: row.khrId,
        },
        index: row.index,
      };
    },
    sortingPerChooseDialogChild(data) {
      console.log(data);
      this.dataList.forEach((ele) => {
        if (data.index == ele.index) {
          ele.khrName = data.khrName;
          ele.khrId = data.khrId;
        }
      });
    },
    submitfy(data) {
      console.log(data);
      this.fayuerendataList = data.tableDataUser;
    },
    addBtn() {
      if (this.dataForm.templateId == undefined) {
        this.$message.warning("请选择模板名称");
      } else {
        this.dialogVisible = true;
        this.$nextTick(() => {
          this.$refs.zhibiaoRef.hetongEnter(0, "htcj");
        });
      }
    },
    fngetTempList() {
      var params = {
        mainId: this.dataForm.templateId,
      };
      this.loading = true;
      getTempListForgzrws(params).then((res) => {
          if(res.data.data[4].isjump=='false'){
            this.iszipingShow = false;
          }else{
            this.iszipingShow = true;
          }
      })
    },
    addZhibiao() {
      this.fullscreenLoadingadd = true;
      addHetongHtzb({
        rows: this.newRows,
        hetongId: 0,
      }).then((res) => {
        this.dataList = this.dataList.concat(res.data.data);
        var indexs = 0;
        this.dataList.forEach((ele) => {
          if (ele.isziping == undefined) {
            this.$set(ele, "isziping", "false");
          }
          if (ele.khrName == undefined || ele.khrId == undefined) {
            this.$set(ele, "khrName", "");
            this.$set(ele, "khrId", "");
          }
          this.$set(ele, "index", indexs);
          indexs++;
        });
        this.resetDataList();
        this.dialogVisible = false;
        this.fullscreenLoadingadd = false;
      });
    },
    getRow(rows) {
      rows = rows.map((item) => {
        item.tgLx = item.tgLx ? item.tgLx : "1";
        return item;
      });
      this.newRows = rows;
    },
    deleteBatch() {
      var data = this.$refs.table.selection;
      data.forEach((ele) => {
        this.dataList.forEach((eles, i) => {
          if (ele.index == eles.index) {
            this.dataList.splice(i, 1);
          }
        });
      });
    },
    copyZhibiao() {},
    closeBtn() {
      this.visible = false;
      this.fayuerendataList = [];
      this.dataForm = {};
      this.dataList = [];
      this.$emit("addChildren", "");
    },
    saveBtn() {
      this.dataForm.bkhrUsers = this.fayuerendataList;
      this.dataForm.details = this.dataList;
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          for (var i = 0; i < this.dataList.length; i++) {
            if (this.dataList[i].khrId == "") {
              this.$message.warning("第" + [i + 1] + "行请选择考核人");
              return;
            }
          }
          if (this.fayuerendataList.length == 0) {
            this.$message.closeAll();
            this.$message.warning("请选被考核人");
          } else {
            this.fullscreenLoading = true;
            saveWorkAssign(Object.assign(this.dataForm))
              .then((res) => {
                this.$message.closeAll();
                this.$message.success("保存成功");
                this.closeBtn();
                this.fullscreenLoading = false;
              })
              .catch(() => {
                this.fullscreenLoading = false;
              });
          }
        } else {
          return false;
        }
      });
    },
    //重组dataList
    resetDataList() {
      this.dataList = this.dataList.map((item) => {
        item.providerList = [];
        item.tgLx = (item.tgLx ? item.tgLx : 1) || "2";
        console.log(item);
        //tgLx等于1是机构，2是个人
        if (item.tgLx == "2") {
          item.dataProviderIdSelect = item.targetUserId;
          item.dataProviderNameSelect = item.targetUserName;
        } else {
          item.dataProviderIdSelect = item.dataProviderId;
          item.dataProviderNameSelect = item.dataProvider;
        }
        if (item.targetUserId) {
          item.providerList.push({
            val: item.targetUserId,
            label: item.targetUserName,
          });
        }
        if (item.dataProviderId) {
          item.providerList.push({
            val: item.dataProviderId,
            label: item.dataProvider,
          });
        }
        if (item.targetValue) {
          item.targetValue = item.targetValue.replace(/(；|;)/g, ";\n");
        }
        return item;
      });
    },
  },
};
</script>
